package com.dabai.qrtools.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.dabai.qrtools.R;
import com.dabai.qrtools.other.ContactUtils;
import com.dabai.qrtools.other.ImageUtils;
import com.dabai.qrtools.qrcode.QRCodeUtils;
import com.dabai.qrtools.utils.DabaiUtils;
import com.dabai.qrtools.utils.ThemeUtils;
import com.dabai.qrtools.utils.ViewUtils;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.chip.Chip;
import com.google.android.material.textfield.TextInputLayout;
import com.permissionx.guolindev.PermissionX;

import java.util.Objects;

public class ContactQrActivity extends AppCompatActivity {


    private Context context;
    private MaterialToolbar mToolbar;
    private TextInputLayout mTil1;
    private TextInputLayout mTil2;
    private Button mButton1;
    private ImageView mImg;
    private Chip mChip1;
    private String qrContent="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_qr);
        initViews();


        context = this;

        ThemeUtils.setAutoUiModeStatusBar(this, this);
        setSupportActionBar(mToolbar);

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        initListenerEvent();

    }

    private void initListenerEvent() {

        mTil1.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                create();
            }
        });
        mTil2.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                create();
            }
        });

        mButton1.setOnClickListener(v -> PermissionX.init(ContactQrActivity.this)
                .permissions(Manifest.permission.READ_CONTACTS)
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        DabaiUtils.showToast(context, "需要读取通讯录权限!");
                    } else {

                        Uri uri = ContactsContract.Contacts.CONTENT_URI;
                        Intent intent = new Intent(Intent.ACTION_PICK, uri);
                        startActivityForResult(intent, 501);

                    }
                }));


        mChip1.setOnClickListener(v -> QRCodeUtils.saveQrImageToDCIM(context, qrContent));

        mImg.setOnClickListener(v -> {

            if (qrContent.isEmpty()){
                return;
            }
            ImageUtils.showBigImage(context,
                    QRCodeUtils.createSimpleQrCodeBitmap(context,qrContent,1000));
        });

        //解决滑动冲突
        ViewUtils.FixScrollViewConflict(mTil1.getEditText());
        //解决滑动冲突
        ViewUtils.FixScrollViewConflict(mTil2.getEditText());


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 501) {


                try {

                    if (data != null) {

                        Uri uri = data.getData();
                        String[] contacts = ContactUtils.getPhoneContacts(context, uri);

                        ViewUtils.setTextInputLayoutText(mTil1, contacts[0]);
                        ViewUtils.setTextInputLayoutText(mTil2, contacts[1]);

                    }

                } catch (Exception e) {
                    Toast.makeText(context, "生成失败,请换一个联系人试试:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        }

    }


    public void create() {
        String text1 = ViewUtils.getTextInputLayoutText(mTil1);
        String text2 = ViewUtils.getTextInputLayoutText(mTil2);

        qrContent = "BEGIN:VCARD\n" + "VERSION:3.0\n" + "FN:" + text1 + "\n" + "TEL:" + text2 + "\n" + "NOTE:QRTools Share\n" + "END:VCARD";
        QRCodeUtils.setImageView(context, mImg, qrContent);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initViews() {
        mToolbar = findViewById(R.id.toolBar);
        mTil1 = findViewById(R.id.til1);
        mTil2 = findViewById(R.id.til2);
        mButton1 = findViewById(R.id.button1);
        mImg = findViewById(R.id.img);
        mChip1 = findViewById(R.id.chip1);
    }
}